using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;

public class ImageDragController : MonoBehaviour, IPointerDownHandler, IDragHandler, IPointerUpHandler
{
    [Header("拖拽设置")]
    public bool enableDrag = true;
    public KeyCode toggleDragKey = KeyCode.F1;
    
    [Header("边界限制")]
    public bool constrainToScreen = true;
    public float screenMargin = 50f;
    
    private RectTransform rectTransform;
    private Canvas canvas;
    private Vector2 dragOffset;
    private bool isDragging = false;
    
    void Start()
    {
        rectTransform = GetComponent<RectTransform>();
        canvas = GetComponentInParent<Canvas>();
        
        // 确保Image可以接收射线检测
        Image image = GetComponent<Image>();
        if (image != null)
        {
            image.raycastTarget = true;
        }
    }
    
    void Update()
    {
        if (Input.GetKeyDown(toggleDragKey))
        {
            ToggleDragMode();
        }
    }
    
    public void OnPointerDown(PointerEventData eventData)
    {
        if (!enableDrag) return;
        
        isDragging = true;
        
        // 计算拖拽偏移
        Vector2 localPoint;
        RectTransformUtility.ScreenPointToLocalPointInRectangle(
            rectTransform, eventData.position, eventData.pressEventCamera, out localPoint);
        dragOffset = localPoint;
        

    }
    
    public void OnDrag(PointerEventData eventData)
    {
        if (!enableDrag || !isDragging) return;
        
        // 直接使用世界坐标进行拖拽，避免复杂的坐标转换
        Vector3 worldPosition;
        if (RectTransformUtility.ScreenPointToWorldPointInRectangle(
            rectTransform.parent as RectTransform, 
            eventData.position, 
            eventData.pressEventCamera, 
            out worldPosition))
        {
            // 设置世界位置
            rectTransform.position = worldPosition;
            
            // 应用边界限制
            if (constrainToScreen)
            {
                ConstrainToScreen();
            }
        }
    }
    
    public void OnPointerUp(PointerEventData eventData)
    {
        if (!enableDrag) return;
        isDragging = false;
    }
    
    private void ConstrainToScreen()
    {
        Vector3 pos = rectTransform.position;
        Vector2 size = rectTransform.sizeDelta;
        
        // 获取屏幕边界
        float minX = size.x / 2 + screenMargin;
        float maxX = Screen.width - size.x / 2 - screenMargin;
        float minY = size.y / 2 + screenMargin;
        float maxY = Screen.height - size.y / 2 - screenMargin;
        
        // 限制位置
        pos.x = Mathf.Clamp(pos.x, minX, maxX);
        pos.y = Mathf.Clamp(pos.y, minY, maxY);
        
        rectTransform.position = pos;
    }
    
    public void ToggleDragMode()
    {
        enableDrag = !enableDrag;
        
        Debug.Log($"拖拽模式: {(enableDrag ? "启用" : "禁用")}");
    }
}